import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:navigator_demo/navigator2pointzero/router/app_route_page.dart';

class AppRouterDelegate extends RouterDelegate<String>
    with PopNavigatorRouterDelegateMixin, ChangeNotifier {
  List<String> _stack;

  RouteFactory _routeFactory;

  AppRouterDelegate({@required RouteFactory routeFactory})
      : assert(routeFactory != null),
        _stack = [],
        _routeFactory = routeFactory;

  static AppRouterDelegate of(BuildContext context) {
    final routeDelegate = Router.of(context).routerDelegate;
    assert(routeDelegate is AppRouterDelegate,
        'routeDelegate should be [AppRouteDelegate]');
    return routeDelegate as AppRouterDelegate;
  }

  @override
  Widget build(BuildContext context) {
    return Navigator(
      key: navigatorKey,
      pages: [
        ..._stack
            .map((name) => AppRouterPage(
                  key: ValueKey(name),
                  arguments: null,
                  routeFactory: _routeFactory,
                  name: name,
                ))
            .toList(),
      ],
      onPopPage: _onPopPage,
    );
  }

  @override
  Future<void> setInitialRoutePath(String configuration) {
    return setNewRoutePath(configuration);
  }

  @override
  Future<void> setNewRoutePath(String configuration) {
    _stack
      ..clear()
      ..add(configuration);
    return SynchronousFuture<void>(null);
  }

  @override
  GlobalKey<NavigatorState> get navigatorKey => GlobalKey<NavigatorState>();

  // Custom route events
  void push(String newRoute) {
    _stack.add(newRoute);
    notifyListeners();
  }

  void pop() {
    if (_stack.isNotEmpty) _stack.removeLast();
    notifyListeners();
  }

  bool _onPopPage(Route<dynamic> route, result) {
    if (_stack.isNotEmpty && _stack.last == route.settings.name) {
      _stack.removeLast();
      notifyListeners();
    }
    return route.didPop(result);
  }
}
